<template>
  <div id="chart"></div>
</template>

<script>
import * as echarts from 'echarts';
import * as XLSX from 'xlsx';
import xlsxFile from '../assets/data/data.xlsx';

export default {
  name: 'BottomLeftChart',
  mounted() {
    this.initChart();
    window.addEventListener('resize', this.resizeChart);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeChart);
  },
  methods: {
    async initChart() {
      const chartDom = document.getElementById('chart');
      this.chart = echarts.init(chartDom);
      try {
        const response = await fetch(xlsxFile);
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        const arrayBuffer = await response.arrayBuffer();
        const workbook = XLSX.read(arrayBuffer, { type: 'array' });

        const sheetName = '主要科学领域国家分布';
        const worksheet = workbook.Sheets[sheetName];
        if (!worksheet) {
          throw new Error('找不到工作表: 主要科学领域国家分布');
        }

        const data = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
        const parsedData = {};
        // 解析数据，按学科和国家整理
        for (let i = 1; i < data.length; i++) {
          const row = data[i];
          // 跳过完全为空或关键列为空的行
          if (!row || row.length < 3 || !row[0] || !row[1] || !row[2]) continue;

          const discipline = row[0].toString().trim();
          const country = row[1].toString().trim();
          // 确保 articles 是数值类型
          const articles = parseInt(row[2], 10);
          if (isNaN(articles)) continue; // 跳过文章数不是数字的行

          if (!parsedData[discipline]) {
            parsedData[discipline] = [];
          }
          parsedData[discipline].push({ name: country, articles });
        }


        const formattedData = Object.entries(parsedData).map(([discipline, countries]) => ({
          discipline,
          countries
        }));

        // 横轴学科
        // 横轴学科
        const disciplines = formattedData.map(d => d.discipline);
        const colors = [
          '#42a5f5', // 蓝
          '#66bb6a', // 绿
          '#ec407a', // 粉
          '#ffa726', // 橙
          '#7e57c2', // 紫
          '#00bcd4', // 青
          '#ff7043', // 橙红
          '#9c27b0', // 深紫
          '#8bc34a', // 黄绿
          '#3f51b5', // 靛蓝
          '#f06292', // 玫红
          '#26a69a', // 青绿
          '#ef5350', // 亮红
          '#ab47bc', // 亮紫
          '#d4e157', // 柠檬黄
          '#29b6f6', // 天蓝
          '#ffca28', // 金黄
          '#8d6e63', // 棕
          '#bdbdbd', // 中灰
          '#78909c'  // 蓝灰
        ];

        // 🔑 收集所有学科出现过的国家
        const allCountries = [
          ...new Set(
            formattedData.flatMap(d => d.countries.map(c => c.name))
          )
        ];

        // 🔑 构建 series，每个 series 对应一个国家
        const series = allCountries.map((country, idx) => ({
          name: country,
          type: 'bar',
          stack: 'total',
          barWidth: '50%',
          itemStyle: { color: colors[idx % colors.length] },
          data: formattedData.map(d => {
            const found = d.countries.find(c => c.name === country);
            if (!found) return { value: null }; // 👈 没有数据时返回 null
            const total = d.countries.reduce((sum, c) => sum + c.articles, 0);
            return {
              value: found.articles,
              ratio: total > 0 ? ((found.articles / total) * 100).toFixed(2) : 0
            };
          })

        }));


        const option = {
          title: {
            text: '主要科学领域国家分布图',
            left: 'center',
            top: '5%',
            textStyle: {
              color: '#c3cbde',
              fontSize: 20,
              fontFamily: 'Microsoft YaHei, sans-serif',
              fontWeight: 'normal'
            }
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: { type: 'shadow' },
            formatter: function (params) {
              const validParams = params.filter(p => p.data.value != null);
              let tip = `<b>${params[0].axisValue}</b><br/>`;
              let total = validParams.reduce((sum, p) => sum + p.data.value, 0);
              validParams.forEach(p => {
                tip += `${p.marker}${p.seriesName}: ${p.data.value} (${p.data.ratio}%)<br/>`;
              });
              tip += `<b>总计: ${total} 篇</b>`;
              return tip;
            }
          },
          //
          legend: {
            data: allCountries,
            bottom: 5,
            type: 'scroll',
            textStyle: {
              color: '#ffffff',
              fontSize: 14
            }
          },
          grid: { left: '5%', right: '5%', top: '15%', bottom: '15%', containLabel: true },
          xAxis: {
            type: 'category',
            data: disciplines,
            axisLabel: {
              color: 'white',
              fontSize: 14,
              interval: 0,
              formatter(value) {
                if (value.length > 4) {
                  return value.slice(0, 2) + '\n' + value.slice(2);
                }
                return value;
              }
            }
          },
          yAxis: {
            type: 'value',
            name: '文章数量',
            nameTextStyle: { color: '#ffffff' },
            axisLabel: { color: 'white', fontSize: 15 }
          },
          series: series
        };


        this.chart.setOption(option);
      } catch (error) {
        console.error('读取文件时出错:', error);
      }
    },
    resizeChart() {
      if (this.chart) this.chart.resize();
    }
  }
};
</script>

<style scoped>
#chart {
  width: 100%;
  height: 320px;
}
</style>
